package remote.service;

import client.common.result.Result;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import remote.common.constant.UrlConstant;
import remote.common.storage.TokenStorage;

import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

public interface ExcelExportService {
    /**
     * 根据年份和月份导出订单详情到 Excel
     *
     * @param year  年份
     * @param month 月份
     * @return 导出结果
     */
    default Result<String> exportOrdersToExcel(String year, String month, String savePath) {
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("year", year);
        requestParam.put("month", month);
        try {
            HttpResponse response = HttpRequest.get(UrlConstant.BASE_URL + "/order/exportByMonth")
                    .form(requestParam)
                    .header("Authorization", TokenStorage.getToken())
                    .execute();
            if (response.getStatus() != 200) {
                return Result.failure(response.getStatus(), "导出失败: " + response.getStatus());
            }
            
            byte[] bytes = response.bodyBytes();
            
            try (FileOutputStream fos = new FileOutputStream(savePath)) {
                fos.write(bytes);
            }
            
            return Result.success("导出成功！保存路径: " + savePath);
        } catch (Exception e) {
            return Result.failure(500, "导出失败: " + e.getMessage());
        }
        
        
    }
    
    /**
     * 根据年份和物料id导出仓库账单到 Excel
     */
    default Result<String> exportBillToExcel(String year, Long materialId, String savePath) {
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("materialId", materialId);
        requestParam.put("year", year);
        
        try {
            HttpResponse response = HttpRequest.get(UrlConstant.BASE_URL + "/materials/exportWarehouseLedger")
                    .header("Authorization", TokenStorage.getToken())
                    .form(requestParam)
                    .execute();
            if (response.getStatus() != 200) {
                return Result.failure(response.getStatus(), "导出失败: " + response.getStatus());
            }
            byte[] bytes = response.bodyBytes();
            
            try (FileOutputStream fos = new FileOutputStream(savePath)) {
                fos.write(bytes);
            }
            return Result.success("导出成功！保存路径: " + savePath);
            
        } catch (Exception e) {
            return Result.failure(500, "导出失败: " + e.getMessage());
        }
    }
}
